package com.gaofei.alipay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.gaofei.alipay.config.AlipayConfig;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@CrossOrigin
public class NotifyController {


    @RequestMapping("notify")
    public String notifyPay(HttpServletRequest request) throws Exception {
        System.out.println("支付了,就会走这个地址!!");
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no"));

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no"));

            //付款金额
            String total_amount = new String(request.getParameter("total_amount"));

            System.out.println("trade_no:"+trade_no+"out_trade_no:"+out_trade_no+"total_amount:"+total_amount);

            //为什么要在这个接口中获取这些参数
            //就是为了拿到这些参数之后,去更新订单表中相应的数据;比如:之前的订单是未支付状态--->已支付状态
            //更新数据库的订单状态,和交易时间
            //TODO
        }else {
            System.out.println("验签失败");
        }
        return "success";
    }
}
